<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="open"
    append-to-body
    title="添加对照"
    width="70%"
    @close="cancel"
  >
    <el-row :gutter="24">
      <el-col :span="8">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
          <el-row :gutter="40">
            <el-col :span="24">
              <el-form-item label="项目分类" prop="itemClass">
                <el-select
                  v-model="form.itemClass"
                  clearable
                  filterable
                  placeholder="请选择项目分类"
                  style="width: 100%"
                  @change="itemClassChange"
                >
                  <el-option
                    v-for="dict in billItemList"
                    :key="dict.dictValue"
                    :disabled="dict.disabled"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="项目名称">
                <el-input v-if="isShow" v-model="form.itemName"
                          @focus="isShowItemNameFocus()">
                </el-input>
                <automatic-completion
                  v-else style="width: 100%"
                  ref="itemAutomatic"
                  :dict-array="dictArray"
                  :table-body-list="tableBodyList"
                  :table-head-list="tableHeadList"
                  :title="itemTitle"
                  @rowClick="rowClick"
                  @itemNameInput="itemNameInput"
                />
              </el-form-item>
              <el-col :span="24">
                <el-form-item label="数量" prop="amount">
                  <el-input
                    v-model="form.amount"
                    placeholder="请输入数量"
                    type="number"
                    @input="amountInput"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目规格" prop="itemSpec">
                  <el-input
                    v-model="form.itemSpec"
                    :disabled="true"
                    placeholder="请输入项目规格"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="单位" prop="units">
                  <el-select
                    v-model="form.units"
                    :disabled="true"
                    filterable
                    placeholder="请选择单位"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="dict in dictDataMap['spec_unit']"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="单价" prop="price">
                  <el-input v-model="form.price" :disabled="true">
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="小计" prop="">
                  <el-input v-model="form.subTotal" :disabled="true">
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
      <el-col :span="16">
        <price-checked-table
          ref="priceCheckTableRef"
          :clinic-item-info="clinicItemInfo"
          :is-show-operation="true"
        />
      </el-col>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {addClinicVsPrice} from "@/api/base/clinicVsPrice";
import {getCurrentPriceList} from "@/api/base/priceList";
// 项目自动补全组件
import AutomaticCompletion from "@/components/AutomaticCompletion/index.vue";
import priceCheckedTable from "@/components/PriceCheckedTable/index.vue";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {jsonStrInObj, priceTableHeadList} from "@/utils/autoComplete";

const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook();
const formRef = ref();
const priceCheckTable = ref();
const itemAutomatic = ref();
const addControlDialog = ref();
const priceCheckTableRef = ref();
const dictDataMap = ref(dictStore.isTypeGetData("bill_item_class_dict", "spec_unit"));
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;

const emits = defineEmits(["selectClinicList"]);
const open = ref(false);
// 确定按钮loading状态
const buttonLoading = ref(false);
// 诊疗项目信息
const clinicItemInfo = ref<any>({});
const form = ref<any>({
  amount: 1,
  subTotal: 0.0,
});
// 诊疗项目下拉框
const billItemList = ref<any[]>([]);
// 已对照项目
const checkedData = ref([]);
const rules = ref({
  itemName: [{required: true, message: "项目名称不能为空", trigger: "blur"}],
  amount: [{required: true, message: "项目数量不能为空", trigger: "blur"}],
});
// 项目选择自动补全窗体名称
const itemTitle = ref("选择项目");
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(priceTableHeadList));
// 项目选择自动补全表格数据
const tableBodyList = ref([]);
// 项目选择自动补全字典数组
const dictArray = ref(["bill_item_class_dict", "spec_unit"]);

/** 取消按钮 */
function cancel() {
  closePopover();
  open.value = false;
  emits("selectClinicList");
  reset();
}

/** 表单重置 */
function reset() {
  form.value.itemName = undefined;
  form.value.priceId = undefined;
  form.value.itemSpec = undefined;
  form.value.units = undefined;
  form.value.price = undefined;
  form.value.subTotal = undefined;
  form.value.clinicItemId = undefined;
  buttonLoading.value = false;
}

/** 打开弹出框 */
function addControlDialogShow(row) {
  open.value = true;
  clinicItemInfo.value = row;
  disposeAddBillItemList();
  // this.$refs.priceCheckTable.init()
  form.value = {
    orgId: row.orgId,
    amount: 1,
    subTotal: 0.0,
  };
}

/** 提交 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.clinicItemId = clinicItemInfo.value.clinicItemId;
      addClinicVsPrice(form.value).then((_res) => {
        priceCheckTableRef.value.selectContrastExistFun();
        reset();
        isShow.value = true
        form.value.itemName = ""
        ElMessage.success("添加成功");
      });
    }
  });
}

/** 项目类别选择事件 */
function itemClassChange(_val) {
  form.value.itemName = "";
}

/** 处理新增页面诊疗项目分类数据 */
function disposeAddBillItemList() {
  billItemList.value = [];
  dictDataMap.value["bill_item_class_dict"].forEach((item) => {
    let billItem: any = {};
    if (item.dictValue === "A" || item.dictValue === "B") {
      billItem.disabled = true;
    }
    billItem.dictValue = item.dictValue;
    billItem.dictLabel = item.dictLabel;
    billItemList.value.push(billItem);
  });
}

/** 自动补全后台查询 */
function getCurrentPriceListFun() {
  form.value.notInSelect = ["A", "B"];
  // 是否过滤已存在的项目标记
  form.value.isFiltrationContrastExist = true;
  form.value.clinicItemId = clinicItemInfo.value.clinicItemId;
  getCurrentPriceList(form.value).then((res) => {
    tableBodyList.value = res.data;
    itemAutomatic.value.init();
  });
}

/** 项目列表行点击事件 */
function rowClick(row) {
  let autoRow = toRaw(row);
  form.value.itemName = autoRow.itemName;
  form.value.priceId = autoRow.priceId;
  form.value.itemSpec = autoRow.itemSpec;
  form.value.units = autoRow.units;
  form.value.price = autoRow.price;
  amountInput(form.value.amount);
  itemAutomatic.value.closePopover();
  isShow.value = true
}

/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
let isShow = ref(true);

function isShowItemNameFocus() {
  debugger
  isShow.value = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.itemName)
    itemAutomatic.value.focusInput()
  })
}


function itemNameInput(itemName) {
  form.value.itemInfo = itemName;
  getCurrentPriceListFun();
}

/** 项目选择关闭事件 */
function closePopover() {
  itemAutomatic.value.itemNameEmpty();
  tableBodyList.value = [];
}

/** 计算小计 */
function amountInput(value) {
  form.value.subTotal = (Number(form.value.price) * Number(value)).toFixed(4);
}

defineExpose({
  addControlDialogShow,
});
</script>
<script lang="ts">
export default {
  name: "addControlDialog",
};
</script>
<style scoped></style>
